#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
# from tqsdk import TqApi, TqAuth
from web.config.tianqin_config import TianqinConfig
from web.models.commodity_future_date_contract_data import CommodityFutureDateContractData
from web.models.tianqin_exclude_code import TianqinExcludeCode
from web.manager.log_manager import LogManager
from web.task.base_task import BaseTask
from web.util.log_util import LogUtil

Logger = LogManager.get_logger(__name__)

"""
调用tianqin的接口，下载商品期货交易的历史合约数据
"""


class TianqinDownloadCollectCommodityFutureDateContractDataTask(BaseTask):
    api = TqApi(web_gui=False, auth=TqAuth(TianqinConfig.Username, TianqinConfig.Password))

    def download_data(self):
        """
        调用tianqin的接口，下载商品期货交易的历史合约数据
        """

        # 下面的代码用于测试
        # api = TqApi(web_gui=True, auth=TqAuth(TianqinConfig.Username, TianqinConfig.Password))
        # quote = api.get_kline_serial("CZCE.CF505", duration_seconds=TianqinConfig.Duration_Seconds,
        #                              data_length=TianqinConfig.Data_Length)
        # array = quote.values
        # list_from_array = array.tolist()

        Logger.info('调用tianqin的接口，下载商品期货交易的历史合约数据')

        # 从日志文件中提取期货代码，并从表tianqin_exclude_code表中读取代码，然后合并去重
        exclude_code_list = self.tianqin_exclude_code_service.find_list()
        exclude_code_list = [exclude_code.code for exclude_code in exclude_code_list if exclude_code.code != None]
        _exclude_code_list = LogUtil.extract_commodity_future_date_contract_data_code_from_log_file(
            "C:\\mywork\\gitcode-repository\\log\\adam3.log")
        e = [item for pair in zip(exclude_code_list, _exclude_code_list) for item in pair]
        exclude_code_list = list(set(e))

        # 拼接交易所前缀和期货代码
        tianqin_contract_prefix_and_code_list = self.commodity_future_exchange_service.concat_tianqin_contract_prefix_and_code()
        if tianqin_contract_prefix_and_code_list != None and len(tianqin_contract_prefix_and_code_list) != 0:

            for tianqin_contract_prefix_and_code in tianqin_contract_prefix_and_code_list:
                prefix = tianqin_contract_prefix_and_code[0]

                # 配置并下载年占一位的数据
                one_year_parameter_list = self.configure_parameter(TianqinConfig.One_Char_Year, TianqinConfig.Month)
                for one_year_parameter in one_year_parameter_list:
                    if prefix + one_year_parameter not in exclude_code_list:
                        self.download_and_save(prefix + one_year_parameter)

                # 配置并下载年占两位的数据
                two_year_parameter_list = self.configure_parameter(TianqinConfig.Two_Char_Year,
                                                                   TianqinConfig.Month)
                for two_year_parameter in two_year_parameter_list:
                    if prefix + two_year_parameter not in exclude_code_list:
                        self.download_and_save(prefix + two_year_parameter)

            self.api.close()

    def configure_parameter(self, year_list, month_list):
        """
        配置参数
        """

        year_month_parameter = list()
        for year in year_list:
            for month in month_list:
                year_month_parameter.append(str(year) + (str(month) if len(str(month)) == 2 else "0" + str(month)))
        return year_month_parameter

    def download_and_save(self, symbol):
        """
        下载并保存数据
        """

        # 创建api实例，设置web_gui=True生成图形化界面
        try:
            quote = self.api.get_kline_serial(symbol, duration_seconds=TianqinConfig.Duration_Seconds,
                                              data_length=TianqinConfig.Data_Length)
            array = quote.values
            list_from_array = array.tolist()

            commodity_future_date_contract_data_list = list()
            for row in list_from_array:
                commodity_future_date_contract_data = CommodityFutureDateContractData()
                commodity_future_date_contract_data.transaction_date = datetime.datetime.fromtimestamp(
                    int(row[0] / 1000000000))
                commodity_future_date_contract_data.open_price = row[2]
                commodity_future_date_contract_data.highest_price = row[3]
                commodity_future_date_contract_data.lowest_price = row[4]
                commodity_future_date_contract_data.close_price = row[5]
                # 成交量
                commodity_future_date_contract_data.turnover = row[6]
                # 持仓量
                commodity_future_date_contract_data.open_interest = row[8]
                commodity_future_date_contract_data.code = row[9]
                commodity_future_date_contract_data_list.append(commodity_future_date_contract_data)

            self.commodity_future_date_contract_data_service.save_commodity_future_date_contract_data_list_for_tianqin(
                commodity_future_date_contract_data_list)
        except Exception as e:
            Logger.warn(e)
            tianqin_exclude_code = TianqinExcludeCode()
            tianqin_exclude_code.code = symbol
            self.tianqin_exclude_code_service.save(tianqin_exclude_code)
            self.api.close()
            self.api = TqApi(web_gui=False, auth=TqAuth(TianqinConfig.Username, TianqinConfig.Password))
